package cl.uchile.microblogging.web;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cl.uchile.microblogging.persistance.FileDAO;
import cl.uchile.microblogging.persistance.model.File;

@Controller
public class FileUploadController {
	static final Logger log = Logger.getLogger(FileUploadController.class);
	@Autowired
	private FileDAO fileDAO;

	@RequestMapping(value = "/upload", produces = "application/json", method = RequestMethod.POST)
	public @ResponseBody
	String[] upload(@RequestParam(value="files[]",required=false) MultipartFile[] files) {
		if(files==null)
			return new String[0];
		ArrayList<String> ids = new ArrayList<String>();
		int i = 0;
		for (MultipartFile file : files) {
			if (file != null && file.getSize() > 0) {
				try {
					File f = new File(
							Base64.encodeBase64String(file.getBytes()),
							file.getContentType());
					fileDAO.save(f);
					ids.add("files/"+f.getId()+"/"+file.getOriginalFilename());
				} catch (Exception e) {
					log.error("Error subiendo archivos", e);
				}
			}
		}
		return ids.toArray(new String[ids.size()]);
	}

	@RequestMapping(value = "/files/{id}/*")
	public void download(HttpServletResponse response, @PathVariable Long id) {

		try {
			File f = this.fileDAO.byId(id);
			IOUtils.copy(
					new ByteArrayInputStream(Base64.decodeBase64(f.getData())),
					response.getOutputStream());
			response.setContentType(f.getType());
			response.flushBuffer();
		} catch (Exception e) {
			log.error("Error descargando archivo", e);
		}

	}

}
